#include "WaitDlg.h"

enum FeedIds
{
	TIMER_ID = 1500
};

BEGIN_EVENT_TABLE( WaitDlg, wxDialog )
EVT_TIMER(TIMER_ID,WaitDlg::CheckConn)
END_EVENT_TABLE()

WaitDlg::WaitDlg(wxWindow *parent, SOCKET hSocket) : WaitDialog (parent)
{
	Socket = hSocket;
	pHeader = NULL;
	Timer.SetOwner (this, TIMER_ID);
	Timer.Start(300);
}

WaitDlg::~WaitDlg(void)
{
}

void WaitDlg::CheckConn( wxTimerEvent& Event)
{
	int nResult;
	int Begin, Elap;

	BrainVisionOn = false; //Setto la Flag del BrainVision Recorder a Stop
	Begin = GetTickCount(); //Inizializzo Contatore tempo

	do
	{
		nResult = GetServerMessage(Socket, &pHeader);
		Elap = GetTickCount()-Begin;
	}while(nResult<= 0 && Elap < 10000);
	
	if (pHeader!=NULL)
	{
		switch(pHeader->nType)
		{
			case 1:			// Start / setup
				BrainVisionOn = true;
			break;
			default:
			break;
		}
	}
	if (BrainVisionOn)
	{
		Timer.Stop();
		this->Hide();
	}
}

int GetServerMessage(SOCKET socket, RDA_MessageHeader** ppHeader)
// Get message from server, if available
// returns 0 if no data, -1 if error, -2 if server closed,  > 0 if ok.
{
	// Use select() to avoid blocking.
	timeval tv; tv.tv_sec = 0; tv.tv_usec = 5000;	// 50 ms.
	fd_set readfds;
	FD_ZERO(&readfds);
	FD_SET(socket, &readfds);
	int nResult = select(1, &readfds, NULL, NULL, &tv);
	if (nResult != 1) return nResult;

	RDA_MessageHeader header;
	char* pData = (char*)&header;
	int nLength = 0;
	bool bFirstRecv = true;
	// Retrieve header.
	while(nLength < sizeof(header))
	{
		int nReqLength = sizeof(header) - nLength;
		nResult = recv(socket, (char*)pData, nReqLength, 0);

		// When select() succeeds and recv() returns 0 the server has closed the connection.
		if (nResult == 0 && bFirstRecv)	return -2;
		bFirstRecv = false;
		if (nResult < 0) return nResult;
		nLength += nResult;
		pData += nResult;
	}

	// Check for correct header GUID.
	if (header.guid != GUID_RDAHeader) return -1;
	*ppHeader = (RDA_MessageHeader*)malloc(header.nSize);
	if (!*ppHeader) return -1;

	memcpy(*ppHeader, &header, sizeof(header));
	pData = (char*)*ppHeader + sizeof(header);

	nLength = 0;
	int nDatasize = header.nSize - sizeof(header);

	// Retrieve rest of block.
	while(nLength < nDatasize)
	{
		int nReqLength = nDatasize - nLength;
		nResult = recv(socket, (char*)pData, nReqLength, 0);
		if (nResult < 0) return nResult;
		nLength += nResult;
		pData += nResult;
	}

	return 1;
}

